# _*_coding:utf-8_*_
from ATS.myLog import logger
from ATS.datamanager import DbImpl as dbimpl
import traceback
import os
from ATS.util import constant as constant


def query_porf_result(ppf, total_sites):
    """
    ppf: XXX.ppf
    """
    ppf_base_name = os.path.splitext(ppf)[0]
    db_path = os.path.join(constant.DB_PATH, ppf_base_name)
    if not os.path.exists(db_path):
        os.mkdir(db_path)
    current_dbfile = os.path.join(db_path, ppf_base_name + '.db')

    final_result = {}
    dbi = None
    try:
        dbi = dbimpl.DbImpl(current_dbfile)
        query_result, site_seq, loop_seq = dbi.fetch_output_data_by_limit(s_list=total_sites, real_time=False)
        if len(query_result) == 0:
            if dbi:
                dbi.release_con()
            logger.log_error("Empty result while query binning result: Empty output data list!")
            return final_result

        #        for tmp_wafer_id in wafers:
        #            if not query_result.has_key(tmp_wafer_id):
        #                continue
        #            wafer_dict = query_result.get(tmp_wafer_id)

        wafer_dict = query_result.values()[0]  # Assume there only one wafer
        for j, site_v in enumerate(total_sites):
            if site_v not in wafer_dict:
                continue
            site_dict = wafer_dict.get(site_v, {})
            site_porf_result = None
            for ssite_j, ssite_db in enumerate(site_dict.keys()):
                ssite_dict = site_dict.get(ssite_db, {})
                for device_j, device_db in enumerate(ssite_dict.keys()):
                    device_dict = ssite_dict.get(device_db)
                    for test_j, test_db in enumerate(device_dict.keys()):
                        test_dict = device_dict.get(test_db)
                        for output_col in test_dict.keys():
                            output_value = test_dict.get(output_col)
                            temp_output_value = ''
                            if isinstance(output_value, list):
                                if len(output_value) > 0:
                                    temp_output_value = str(output_value[0])
                            else:
                                temp_output_value = str(output_value)
                            if output_col.lower().endswith(constant.INK_POSTFIX):
                                try:
                                    if site_porf_result is None:
                                        site_porf_result = int(temp_output_value)
                                    else:
                                        site_porf_result = site_porf_result * int(temp_output_value)
                                except:
                                    logger.log_error("Invalid PorF output for column %s with value %s!" % (
                                        output_col, temp_output_value))
                                    site_porf_result = 1
            final_result[site_v] = site_porf_result
        return final_result
    except:
        logger.log_error("Error while query binning result: %s" % traceback.format_exc())
        return []
    finally:
        if dbi:
            dbi.release_con()
